package leetCode;

import java.util.ArrayList;
import java.util.List;

public class Q54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int total = m*n;
        ArrayList<Integer> res = new ArrayList<>();

        // 0右 1下 2 左 3上
        int ori = 0;
        int x = 0,y = 0;
        int rwall = n-1;
        int dwall = m-1;
        int lwall = 0;
        int uwall = 0;

        for(int i=0;i<total;i++){
            //walk
            switch (ori){
                case 0:
                    res.add(matrix[x][y]);
                    if(y == rwall){
                        ori = 1;
                        rwall--;
                        x++;
                    }else {
                        y++;
                    }
                    break;
                case 1:
                    res.add(matrix[x][y]);
                    if(x == dwall){
                        ori = 2;
                        dwall--;
                        y--;
                    }else {
                        x++;
                    }
                    break;
                case 2:
                    res.add(matrix[x][y]);
                    if(y == lwall){
                        ori = 3;
                        lwall++;
                        x--;
                    }else {
                        y--;
                    }
                    break;
                case 3:
                    res.add(matrix[x][y]);
                    if(x == uwall){
                        ori = 0;
                        uwall--;
                        y++;
                    }else {
                        x--;
                    }
                    break;
            }
        }
        return res;
    }
}
